var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var ejs = require('ejs');
var indexRouter = require('./app_server/routes/index');
var deputeRouter = require('./app_server/routes/deputeRouter');
var checkRouter = require('./app_server/routes/checkRouter');
var businessRouter = require('./app_server/routes/businessRouter');

var userRouter = require('./app_server/routes/user');//user+staff+part---ok
var taskRouter = require('./app_server/routes/task');//task+workpiece+workcount+tech---ok
var operationRouter = require('./app_server/routes/operation');//operation+photo+taskPaper(???)---ok
var echoRouter = require('./app_server/routes/echo');//echo+report
var projectRouter = require('./app_server/routes/project');//project---ok
var connection = require('./app_server/backjs/node_mysql');//???Refresh

var bodyParser = require('body-parser');
var session = require('express-session');
var app = express();
app.engine('html', ejs.__express);
// view engine setup
app.set('views', path.join(__dirname, '/app_server/views'));
app.set('view engine', 'html');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
    resave: false, //添加 resave 选项
    saveUninitialized: true, //添加 saveUninitialized 选项
    secret: 'aF,.j)wBhq+E9n#aHHZ91Ba!VaoMfC', // 建议使用 128 个字符的随机字符串
    cookie: { maxAge: 20 * 1000 * 60 }
}));
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    console.log(err);
    // render the error page
    res.status(err.status || 500);
});

//尝试解决频繁崩溃
process.on('uncaughtException', function (err) {
    console.log(err.stack);
    console.log('NOT exit...');
});

app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    next();
});
app.use(function (req, res, next) {
    if (req.session.user) {
        //用户登录过
        next();
    } else {
        //解析用户请求路径
        var arr = req.url.split('/');
        //去除get请求携带的参数
        for (var i = 0; i < arr.length; i++) {
            arr[i] = arr[i].split('?')[0];
        }
        if (arr.length > 1) {
            if (arr[1] === 'login' || arr[1].indexOf('getCode') != -1 || arr[1].indexOf('register') != -1) { ///if (arr[1] === 'login'||arr[1].indexOf('register')!=-1) {
                next();
            } else {
                res.redirect(302, "/login");
                res.end();
            }
        }
    }
});
function Refresh() {
    connection.query("select user_id from user where user_id = 10", function (err, rs) {
        // console.log(rs);
    });
    setTimeout(Refresh, 1000 * 60);
}
Refresh();
app.use('/', indexRouter);
app.use('/depute', deputeRouter);
app.use('/check', checkRouter);
app.use('/business', businessRouter);


app.use('/user', userRouter);
app.use('/task', taskRouter);
app.use('/op', operationRouter);
app.use('/echo', echoRouter);

// error handler
app.use('/pj', projectRouter);
module.exports = app;
